package struct.intermediate.queue;

import struct.primary.linked.LinkedList;

/**
 * @author MAX
 * @version 1.0
 * @description 中级数据结构-链式循环队列
 * @date 2022/1/14 11:19
 */
public class LinkedLoopQueue<E> implements Queue<E> {

    private Node dummyHead;
    private Node tail;
    private int size;

    public LinkedLoopQueue() {
        dummyHead = new Node(null);
        size = 0;
    }

    @Override
    public void enqueue(E e) {
        dummyHead.next = new Node(e, dummyHead.next);
        size++;
    }

    @Override
    public E dequeue() {
        if(isEmpty()) throw new RuntimeException("Loop Queue Empty");
        Node cur = dummyHead.next;
        Node prev = null;
        while (cur.next != null) {
            prev = cur;
            cur = cur.next;
        }
        if(prev != null) prev.next = null;

        return cur.e;
    }

    @Override
    public E getFront() {
        return null;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    private class Node {
        public E e;
        public Node next;

        public Node(E e) {
            this(e, null);
        }

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        Node cur = dummyHead.next;
        while (cur != null) {
            res.append(cur.e).append("->");
            cur = cur.next;
        }
        res.append("NULL");
        return res.toString();
    }
}
